import numpy as np
import pandas as pd
import sys
def ism():
    #data_path = sys.argv[1]
    #client = HdfsClient(hosts="192.168.1.121, 9000", user_name="admin")
    #fp = client.open(data_path)
    fp='./ISM_matrix.csv'
    data = np.loadtxt(fp, delimiter=',')
    adjacency_matrix = np.array(data)
    M = adjacency_matrix.shape[1]
    N = adjacency_matrix.shape[0]
    I = np.identity(adjacency_matrix.shape[1])
    new_matrix = adjacency_matrix + I
    #old_matrix = new_matrix
    m = 0
    step = 1
    while m == 0:
        old_matrix = new_matrix
        new_matrix = old_matrix * new_matrix
        for i in range(len(new_matrix)):
            for j in range(len(new_matrix)):
                if new_matrix[i, j] >= 1:
                    new_matrix[i, j] = 1
        step += 1
        # 求解打印出可达矩阵并保存为文件
        if (old_matrix == new_matrix).all():
            m = 1
            # print(new_matrix)
            #pd_matrix = pd.DataFrame(new_matrix)
            #pd_matrix.to_csv('./可达矩阵(45).csv')
    # 元素分级
    P = np.array(new_matrix)

    zero = np.zeros(shape=(len(P), len(P)))
    result = np.zeros((N, M))
    r = 1
    al = 0
    while not (P == zero).all():
        for i in range(0, len(P)):
            R = [x + 1 for (x, val) in enumerate(P[i, :]) if val == 1]
            A = [x + 1 for (x, val) in enumerate(P[:, i]) if val == 1]
            C = set(R).intersection(set(A))  # 返回交集
            if len(C) == len(R) and len(R) != 0 and len(A) != 0:
                # 打印出分级结果
                #print('第' + str(r) + '级元素为' + str(i + 1))
                print('The' + str(r) + 'level element is' + str(i + 1))
                P[i, i] = 0
                result[r - 1, al] = str(i + 1)
                al = al + 1
        for x in range(0, len(P)):
            if P[x, x] == 0:
                P[x, :] = 0
                P[:, x] = 0
        r += 1
    # 将分级的结果以矩阵的形式展示
    print("result")
    print(result)
    result_matrix = pd.DataFrame(result)
    result_matrix.to_csv('./分级(45).csv')
if __name__ == '__main__':ism()